 // userPageB/pages/userStore/cardDetail/cardDetail.js
 const app = getApp()
 const WXAPI = require("../../../../api/api")
 const WXAPINEW = require("../../../../api/newApi")
 Page({

   /** 
    * 页面的初始数据
    */
   data: {
     nvabarData: {
       showCapsule: 1, // 是否显示左上角图标   1表示显示    0表示不显示
       title: '预付卡详情', // 导航栏 中间的标题
       textColor: '#fff', // 标题颜色
       bgColor: '', // 导航栏背景颜色
       isColor: false,
       isScrollY: '',
       isShare: '' //是否来自分享 0 :不是，1：是
     },
     nvabarDataTwo: {
       showCapsule: 1, // 是否显示左上角图标   1表示显示    0表示不显示
       title: '预付卡详情', // 导航栏 中间的标题
       textColor: '#2C3241', // 标题颜色
       bgColor: '#FFFFFF', // 导航栏背景颜色
       isloading: true,
       isColor: true,
       //  backUrl: '/pages/assets/assets'
       backUrl: '/pages/userMarket/userMarket'
     },
     imgHttp: app.globalData.imgHttp,
     appid: app.globalData.appid,
     code: '',
     assetId: '',
     merchantId: '',
     cardData: {},
     referrerId: '',
     typePath: '', //从哪里过来的
     cardName: '',
     activitys: [], //充值活动列表
     storesShow: true,
     ismaidian: false,
     authorizaData: {},
     giveGoods: [], //计费卡赠送物品
     money: '',
     type: '', //判断从哪个页面进入参数
     buttonNo: false,
     isScrollY: false,
     tipShow: false,//签约保险说明弹窗
   },

   /**
    * 生命周期函数--监听页面加载
    */
   onLoad: function (options) {
     this.data.nvabarData.isShare = options.isShare
     this.data.type = options.type
     var assetId = options.assetId
     var merchantId = options.merchantId
     var referrerId = options.referrerId
     // var assetId = '1468475854777610242'
     // var merchantId = '1468467205111934977'
     let pages = getCurrentPages();
     if (pages.length > 1) {
       //从店铺详情过来的不显示店铺信息
       console.log("pages['0'].route", pages[pages.length - 2].route)
       if (pages[pages.length - 2].route == 'userPageB/pages/userStore/storesDetails/storesDetails' || pages[pages.length - 2].route == 'userPageB/pages/userStore/theCards/theCards') {
         this.setData({
           storesShow: false,
         })
       }
     }
     this.data.merchantId = merchantId
     this.setData({
       assetId: assetId,
       referrerId: referrerId,
       mobbleBottom: app.mobile.mobbleBottom,
       merchantId: merchantId
     })

     this.getDetail()
   },
   /**
    * 生命周期函数--监听页面显示
    */
   onShow: function () {
     wx.removeStorageSync('signInfo')
     this.dialog = this.selectComponent("#auth_dialog");
     var token = wx.getStorageSync('token')
     if (token == '') {
       this.getCode()
       this.setData({
         ismaidian: true,
       })
     } else {
       this.setData({
         ismaidian: false,
       })
     }
   },

   getSuccess() { //授权成功
     console.log('成功成功++++++')
     this.handlepay()
   },
   //卡详情
   getDetail() {
     var id = this.data.assetId
     var merchantId = this.data.merchantId ? this.data.merchantId : ''
     var data = {
       assetId: id,
       merchantId: merchantId,
       type: this.data.type
     }
     WXAPI.customerCardDetail(data, (res) => {
       if (res.code == 200) {
         console.log('卡详情', res)
         const {
           result
         } = res
         if (result.chargeGiveDTOList.length > 1 && result.chargeGiveDTOList[0].powerName == "赠送金额") {
           this.data.giveGoods = result.chargeGiveDTOList.splice(0, 1);
         }
         console.log(this.data.giveGoods)
         this.data.activitys = result.activitys
         let ls = result.refundRules.map((item) => {
           if (item.refundRule.indexOf(">") != -1) {
             item.isActive = true
           } else {
             item.isActive = false
           }
           return item
         })
         let assls = result.assetIntroduces.map((item) => {
           if (item.assetIntroduce.indexOf(">") != -1) {
             item.isActive = true
           } else {
             item.isActive = false
           }
           return item
         })
         var money = result.worth - result.buyMoney
         this.setData({
           money: Math.round(money * 100) / 100,
           cardData: result,
           giveGoods: this.data.giveGoods,
           refundRuleLs: ls,
           activitys: this.data.activitys,
           assls: assls,
           buttonNo: true
         })

         if (result.cardType == 1) {
           this.data.cardName = '股东卡'
         } else if (result.cardType == 2) {
           this.data.cardName = '计次卡'
         } else if (result.cardType == 3) {
           this.data.cardName = '计费卡'
         } else if (result.cardType == 4) {
           this.data.cardName = '课时卡'
         } else if (result.cardType == 5) {
           this.data.cardName = '体验卡'
         }
         this.setData({
           cardName: this.data.cardName
         })
       } else {
         this.setData({
           buttonNo: false
         })
       }
     })
   },
   //去往店铺
   tomerchant() {
     var id = this.data.cardData.shopId
     var data = {
       shopId: id
     }
     WXAPINEW.isDeactivate(data, (res) => {
       if (res.code == 200) {
         wx.redirectTo({
           url: '/userPageB/pages/userStore/storesDetails/storesDetails?shopId=' + id,
         })
       }
     })
   },
   //拨打电话
   freeTell() {
     wx.makePhoneCall({
       phoneNumber: this.data.cardData.phone,
     })
   },
   //立即购买
   handlepay() {
     var assetId = this.data.cardData.assetId
     var referrerId = this.data.referrerId
     var merchantId = this.data.cardData.merchantId
     if (!referrerId) {
       referrerId = ''
     }
     // wx.navigateTo({
     //   url: '/userPageB/pages/userStore/cardPay/cardPay?assetId='+assetId+'&referrerId='+referrerId+'&merchantId='+merchantId,
     // })
     wx.navigateTo({
       url: '/userPageB/pages/userStore/cardPayNew/cardPayNew?assetId=' + assetId + '&referrerId=' + referrerId + '&merchantId=' + merchantId,
     })
   },
   //查看余额
   handleDetail(e) {
     var assetId = e.currentTarget.dataset.assetid
     var id = e.currentTarget.dataset.id
     wx.navigateTo({
       url: '/ecCanvas/pages/myShareholderCard/otherCarddetail/otherCarddetail?assetId=' + assetId + '&id=' + id,
     })
   },
   //查看合同
   handleContract(e) {
     var url = this.data.imgHttp + e.currentTarget.dataset.url
     var index = url.lastIndexOf("\.");
     var type = url.substring(index + 1, url.length);
     wx.showLoading({
       title:'加载中',
       mask: true
     })
     wx.downloadFile({
       url: url,
       header: {},
       success: function (res) {
         var filePath = res.tempFilePath;
         console.log(filePath);
         wx.openDocument({
           filePath: filePath,
           fileType: type,
           success: function (res) {
             console.log('打开文档成功')
           },
           fail: function (res) {
             console.log("1111111111111", res);
           },
           complete: function (res) {
             console.log("22222222222222", res);
           }
         })
         wx.hideLoading()
       },
       fail: function (res) {
         console.log('文件下载失败');
         wx.hideLoading()
       },
       complete: function (res) {},
     })
     //  app.preventActive(() => {

     //  })
   },
   //查看保险合约
   lookInsuranceContract(e) {
     let insuranceContract = e.currentTarget.dataset.contract
     var url = this.data.imgHttp + insuranceContract
     var index = url.lastIndexOf("\.");
     var type = url.substring(index + 1, url.length);
     wx.showLoading({
      title:'加载中',
      mask: true
    })
     wx.downloadFile({
       url: url,
       header: {},
       success: function (res) {
         var filePath = res.tempFilePath;
         console.log(filePath);
         wx.openDocument({
           filePath: filePath,
           fileType: type,
           success: function (res) {
             console.log('打开文档成功')
           },
           fail: function (res) {
             console.log("1111111111111", res);
           },
           complete: function (res) {
             console.log("22222222222222", res);
           }
         })
         wx.hideLoading()
       },
       fail: function (res) {
         console.log('文件下载失败');
         wx.hideLoading()
       },
       complete: function (res) {},
     })
   },
   questionTip() { //预付无忧问号点击
     wx.showModal({
       title: '预付无忧',
       content: '平台与保险公司联合推出预付无忧保险活动。商家为店铺申请投保，在投保期限内，消费者购买该商家预付卡享时有保险服务，在投保期内因商户原因无法提供服务时，消费者可联系平台，由平台协商进行赔付事宜。',
       showCancel: false
     })
   },
   //签约保险说明弹窗
  signedView(){
    this.setData({
      tipShow: true
    })
  },
   /*
    * 页面滚动
    **/
   onPageScroll(e) { //监听页面滚动距离
     var that = this;
     var scrollY = e.scrollTop
     if (scrollY > 50) {
       that.setData({
         ['nvabarData.textColor']: '#000',
         ['nvabarData.isScrollY']: true,
         ['nvabarData.isColor']: true,
       })
       wx.setNavigationBarColor({
         frontColor: '#000000',
         backgroundColor: '#000000',
       })
     } else if (scrollY < 50) {
       that.setData({
         ['nvabarData.textColor']: '#fff',
         ['nvabarData.isScrollY']: false,
         ['nvabarData.isColor']: false,
       })
       wx.setNavigationBarColor({
         frontColor: '#ffffff',
         backgroundColor: '#ffffff',
       })
     }
   },
   //授权手机号码
   getPhoneNumber: function (e) {
     let that = this;
     console.log(e.detail.errMsg)
     console.log(e.detail.iv)
     console.log(e.detail.encryptedData)
     console.log(e.detail.errMsg)
     if (e.detail.errMsg == 'getPhoneNumber:ok') {
       console.log("点击事件", that.data.code)
       let data = {
         appid: that.data.appid,
         code: that.data.code,
         encryptedData: e.detail.encryptedData,
         iv: e.detail.iv,
         source: app.globalData.source, //用户来源
       }
       WXAPI.newgetPhone('', data, (res) => {
         let data = res.result
         if (res.result) {
           if (data.token) {
             wx.setStorageSync('token', data.token)
             wx.setStorageSync('phone', data.phone)
             this.handlepay()
           } else {
             var authorizaData = {}
             app.globalData.phone = data.phone;
             authorizaData.sessionKey = data.sessionKey;
             authorizaData.encryption = data.encryption;
             authorizaData.phone = data.phone;
             this.setData({
               authorizaData: authorizaData
             })
             this.dialog.showUser()
           }

         }

       })
     } else if (e.detail.errMsg == 'getPhoneNumber:fail user deny') {
       //ios拒绝授权  
       that.setData({
         isphoneBox: false
       })
       that.triggerEvent("notokenFuntion");
     } else if (e.detail.errMsg == 'getPhoneNumber:fail:user deny') {
       //安卓拒绝授权    
       that.setData({
         isphoneBox: false
       })
       that.triggerEvent("notokenFuntion");
     }
   },
   getCode() {
     // 登录 
     let that = this;
     wx.login({
       success: function (res) {
         if (res.code) {
           that.setData({
             code: res.code
           })
           console.log('获取code', that.data.code)
         } else {
           console.log('获取code失败', res.errMsg)
         }
       }
     })
   },

   /**
    * 页面相关事件处理函数--监听用户下拉动作
    */
   onPullDownRefresh: function () {
     setTimeout(() => {
       wx.stopPullDownRefresh();
     }, 1000);
   },

   /**
    * 用户点击右上角分享
    */
   onShareAppMessage: function (res) {
     console.log('this.data.assetId', this.data.assetId)
     console.log('this.data.merchantId', this.data.merchantId)
     if (res.from == 'button') {
       return {
         title: this.data.cardData.assetName,
         path: 'userPageB/pages/userStore/cardDetail/cardDetail?assetId=' + this.data.assetId + "&merchantId=" + this.data.merchantId,
       }
     }
     return {
       title: this.data.cardData.assetName,
       path: 'userPageB/pages/userStore/cardDetail/cardDetail?assetId=' + this.data.assetId + '&isShare' + '1' + "&merchantId=" + this.data.merchantId,
     }
   }
 })